package com.assets.CanniBalize;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;

import com.assets.Adapter.Input_Adapter_item1;
import com.assets.Adapter.Input_Adapter_item_new;
import com.assets.BaseActivity;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Receive.add_admin;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.Shift.Allot_department;
import com.assets.Shift.Allot_unit;
import com.assets.bean.Input_item1;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.assets.util.SoftKeyBoardListener;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;

import okhttp3.*;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class CanniBalize_add extends BaseActivity {
    private ImageView fh;
    private List<String> assetId = new ArrayList<>();//资产id
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private TextView title_text, tv_company_name, tv_place, tv_manager, divisionName;
    //admin——id管理员id，单位id。位置id
    private String placeId = "", divisionId = "", companyId = "", managerId;
    private EditText allot_remark, et_num, jifang, jigui;
    private Button up_bt, scan_img, btn_rfid;//上传数据，扫码
    private LinearLayout ll_company, ll_place, ll_manager, ll_submit;
    private CanniBalize_add content;
    private String url = "http://" + Url.IP + "/api/assetScanAllotQuery";//获取资产信息url
    private String url_up = "http://" + Url.IP + "/api/allotAdd";//上传
    private List<Input_item1> data = new ArrayList<>();//扫码
    private ListView lv_list;
    private String place;
    private String aaa;

    @Override
    public int intiLayout() {
        return R.layout.cannibalize_add;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        content = this;
    }

    @Override
    public void initView() {
        et_num = (EditText) findViewById(R.id.et_num);
        et_num.setFocusableInTouchMode(true);
        et_num.requestFocus();
        up_bt = (Button) findViewById(R.id.allot_upload);
        scan_img = (Button) findViewById(R.id.scan_img);
        allot_remark = (EditText) findViewById(R.id.allot_remark);
        jifang = findViewById(R.id.jifang);
        jigui = findViewById(R.id.jigui);
        fh = (ImageView) findViewById(R.id.fh);
        title_text = (TextView) findViewById(R.id.title_text);
        ll_company = (LinearLayout) findViewById(R.id.ll_company);
        ll_manager = (LinearLayout) findViewById(R.id.ll_manager);
        tv_company_name = (TextView) findViewById(R.id.tv_company);
        tv_manager = (TextView) findViewById(R.id.tv_manager);
        tv_place = (TextView) findViewById(R.id.site_tv);
        ll_place = (LinearLayout) findViewById(R.id.site_ll);
        lv_list = (ListView) findViewById(R.id.fragment2_list);
        divisionName = (TextView) findViewById(R.id.receive_section);
        ll_submit = (LinearLayout) findViewById(R.id.ll_submit);
        initSoftKeyBoardListener();
        LinearLayout ll_dept = (LinearLayout) findViewById(R.id.add_department);
        ll_dept.setOnClickListener(v -> {//事业部
            if (TextUtils.isEmpty(companyId)) {
                showToast("请先选择公司");
                return;
            }
            tv_manager.setText("");//管理人
            managerId = "";
            Intent intent = new Intent(this, Allot_department.class);
            intent.putExtra("department_id", companyId);
            startActivityForResult(intent, 2);
        });
        btn_rfid = findViewById(R.id.btn_rfid);
        btn_rfid.setOnClickListener(v -> {
            String rfidTitle = btn_rfid.getText().toString();
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
        initRFID();
    }


    @Override
    public void initData() {
        title_text.setText("添加调拨单");
        lv_list.setOnItemLongClickListener((parent, view, position, id) -> {
            showTipDialog(aBoolean -> {
                if (aBoolean){
//                    lv_data.remove(data.get(position).getCode_number());
                    data.remove(position);
                    Input_Adapter_item_new adapter_item = new Input_Adapter_item_new(content, R.layout.input_adapter_item, data);
                    lv_list.setAdapter(adapter_item);
                }
            },"确认删除");
            return true;
        });

        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i = 0; i < data.size(); i++) {
//                    if (et_num.getText().toString().trim().equals(data.get(i).getCode_number())) {
//                        Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                }
                String code = et_num.getText().toString().trim();
                if (!code.equals("") && et_num.length() > 9) {
                    if (!lv_data.contains(code)) {
                        requestAssetNumberData(code);
                    } else {
                        Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
                    }
                } else {
//                    Toast.makeText(content, "错误的格式", Toast.LENGTH_SHORT).show();
                }
            }
        });
        fh.setOnClickListener(v -> finish());
        //调入公司
        ll_company.setOnClickListener(v -> {
            divisionName.setText("");//事业部
            divisionId = "";
            tv_manager.setText("");//管理人
            managerId = "";
            Intent dept = new Intent(content, Allot_unit.class);
            startActivityForResult(dept, 1);
        });
        //管理人
        ll_manager.setOnClickListener(v -> {
//            if (TextUtils.isEmpty(companyId)) {
//                showToast("请先选择公司");
//                return;
//            }
            Log.d("无敌最俊朗", "companyId: " + companyId);
            Intent intent = new Intent(content, add_admin.class);
            intent.putExtra("company_id", companyId);
            startActivityForResult(intent, 4);
        });
        ll_place.setOnClickListener(v -> {
            Intent intent = new Intent(content, Shift_site.class);
            startActivityForResult(intent, 5);
        });
        //扫码
        scan_img.setOnClickListener(v -> startQrCode());
        //提交
        up_bt.setOnClickListener(v -> {
            if (data.size() <= 0) {
                showToast("请扫码需要调拨的资产");
                return;
            }
//            if (TextUtils.isEmpty(companyId)) {
//                showToast("请完善数据");
//                return;
//            }
            new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position == 0) {
                        assetId.clear();
                        for (int i = 0; i < data.size(); i++) {
//                            assetId.add(data.get(i).getCode_number());
                        }
                        upload();
                    }
                }
            }).setCancelable(true).show();
        });
    }

    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                if (map.containsKey(epc)) {
                    return;
                }
                map.put(epc, "");
                requestAssetNumberRFID(epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                btn_rfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                btn_rfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode == 1 && resultCode == 1) {
            companyId = datas.getExtras().getString("company_id");
            String name = datas.getExtras().getString("company_name");
            tv_company_name.setText(name);
        }
        //事业部
        if (requestCode == 2 && resultCode == 2) {
            divisionId = datas.getExtras().getString("dept_id");
            String name = datas.getExtras().getString("dept_name");
            divisionName.setText(name);
            LogUtils.d(divisionId);
        }
        //管理人
        if (requestCode == 4 && resultCode == 7) {
            managerId = datas.getExtras().getString("admin_id");
            String name = datas.getExtras().getString("admin_name");
            tv_manager.setText(name);
            LogUtils.d(managerId + name);
        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            if (!lv_data.contains(scanResult)) {
                requestAssetNumberData(scanResult);
            } else Toast.makeText(content, "该资产已存在列表", Toast.LENGTH_SHORT).show();
        }
        if (requestCode == 5 && resultCode == 3) {
            tv_place.setText(datas.getExtras().getString("site_name"));
            placeId = datas.getExtras().getString("site_id");
        }
    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void requestAssetNumberData(final String assetNumber) {
        Map<String, String> map = new HashMap<>();
//        map.put("assetNumber", assetNumber);
        map.put("rfid", assetNumber);
        map.put("userId", Since_case.getInstance().getUserId());
//        post(url, map, responseData -> {
//            handleAssetData(responseData);
//        });
        rfidPostSao("这个是华哥新增的调拨读卡", map, responseData -> {
            handleAssetData(responseData);
        }, () -> {
            this.map.remove(assetNumber);
        });
    }

    private void requestAssetNumberRFID(final String epc) {
        Map<String, String> map = new HashMap<>();
        map.put("rfid", epc);
        map.put("userId", Since_case.getInstance().getUserId());
        rfidPost("这个是华哥新增的调拨读卡", map, responseData -> {
            handleAssetData(responseData);
        }, () -> {
            this.map.remove(epc);
        });
//        post(url, map, responseData -> {
//            LogUtils.d("epc：" + epc + "--" + responseData);
//            handleAssetData(responseData);
//        }, () -> {
//            this.map.remove(epc);
//        });
    }

    private void handleAssetData(String responseData) {
        LogUtils.d(responseData);
        Log.d("无敌最俊朗", "调拨加字段: " + responseData);
        try {
            JSONObject jsonObject = new JSONObject(responseData);
            if (jsonObject.getString("state").equals("1")) {
                JSONObject json = jsonObject.getJSONObject("asset");
                String assetName = json.getString("assetName");
                String deptId = json.getString("deptId");
                String assetNumber = json.getString("assetNumber");

                if (lv_data.contains(assetNumber)) {
                    showToast("该资产已存在列表");
                    return;
                }
                lv_data.add(assetNumber);
                String userId = "闲置、未使用";
                //广州中旭  ZT 李11 广州
                place = json.getString("place");
                aaa = json.getString("aaa");
                String model = json.getString("model");
                String type = json.getString("type");
                String image = json.optString("image");
                String jifang = json.optString("financialCode");
                String jigui = json.optString("accountant");

                if (!TextUtils.isEmpty(image)) {
                    image = "http://" + Url.IP + image;
                }
//                data.add(0, new Input_item1(image, assetName, deptId, assetNumber, userId, model, place, "", jifang, jigui));
                Input_Adapter_item_new adapter_item = new Input_Adapter_item_new(content, R.layout.input_adapter_item, data);
                runOnUiThread(() -> {
                    showToast("添加成功");
                    lv_list.setAdapter(adapter_item);
                });
            }
            if (jsonObject.getString("state").equals("0")) {
                showToast("失败");
            }
            if (jsonObject.getString("state").equals("2")) {
                showToast("资产不存在");
            }
            if (jsonObject.getString("state").equals("3")) {
                showToast("当前资产已报废, 无法调拨");
            }
            if (jsonObject.getString("state").equals("4")) {
                showToast("资产不属于当前用户管理");
            }
        } catch (JSONException e) {
            e.printStackTrace();
            LogUtils.d("异常");
        }
    }


    private void upload() {

        Map<String, String> map = new HashMap<>();
        map.put("inunit", companyId);
        map.put("division", divisionId);
        map.put("userId", Since_case.getInstance().getUserId());
        map.put("admin", managerId);
        map.put("place", placeId);
        map.put("outPlace", aaa);
        map.put("assetNumbers", String.valueOf(assetId));
        map.put("remark", allot_remark.getText().toString());
        map.put("jifang", jifang.getText().toString().trim());
        map.put("jigui", jigui.getText().toString().trim());
        Asset numberByIds = MyDataBase.init(content).assetDao().getNumberByIds(assetId.get(0));
        map.put("newOutPlace", numberByIds.getPlace());

        submitPost("这个是华哥新增的提交本地接口", map, responseData -> {
            Log.d("无敌最俊朗", "responseData: " + responseData);

            try {
                JSONObject jsonObject = new JSONObject(responseData);
                if (jsonObject.getString("state").equals("1")) {
                    finish();
                    showToast("提交成功");
                }
                if (jsonObject.getString("state").equals("0")) {
                    showToast("提交失败");
                }
            } catch (JSONException e) {
                showToast("数据解析异常");
                e.printStackTrace();
            }
        });

//        OkHttpClient client = new OkHttpClient
//                .Builder()
//                .hostnameVerifier(new AllowAllHostnameVerifier())
//                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                .readTimeout(500, TimeUnit.SECONDS)
//                .build();//创建OkHttpClient对象。
//        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
//        formBody.add("inunit", companyId)
//                .add("division", divisionId)
//                .add("userId", Since_case.getInstance().getUserId())
//                .add("admin", managerId)
//                .add("place", placeId)
//                .add("assetNumbers", String.valueOf(assetId))
//                .add("remark", allot_remark.getText().toString()); //传递键值对参数
//
//        LogUtils.d("公司id" + companyId + "事业部" + divisionId + "管理人" + managerId + "存放位置" + placeId + "二维码" + assetId + "备注" + allot_remark.getText().toString());
//
//        Request request = new Request.Builder()//创建Request 对象。
//                .url(url_up)
//                .post(formBody.build())//传递请求体
//                .build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                //回调方法的使用与get异步请求相同
//                showToast("连接服务器失败");
//                e.printStackTrace();
//                LogUtils.d("异常");
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                final String responseData = response.body().string();
//                LogUtils.d(responseData);
//                //回调方法的使用与get异步请求相同
//                try {
//                    JSONObject jsonObject = new JSONObject(responseData);
//                    if (jsonObject.getString("state").equals("1")) {
//                        finish();
//                        showToast("提交成功");
//                    }
//                    if (jsonObject.getString("state").equals("0")) {
//                        showToast("提交失败");
//                    }
//                } catch (JSONException e) {
//                    showToast("数据解析异常");
//                    e.printStackTrace();
//                }
//            }
//        });
    }

    private void initSoftKeyBoardListener() {
        SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(this);
        softKeyBoardListener.setOnSoftKeyBoardChangeListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                ll_submit.setVisibility(View.INVISIBLE);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 1);
                params.height = 1;
                params.topMargin = 0;
                params.bottomMargin = 0;
                ll_submit.setLayoutParams(params);
            }

            @Override
            public void keyBoardHide(int height) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                ll_submit.setLayoutParams(params);
                ll_submit.setVisibility(View.VISIBLE);
            }
        });
    }


}

